
-- ( 统计类：单个worker进程内的统计，不跨server )

local assert     = assert
local require    = require
local bit        = bit
local coroutine  = coroutine
local debug      = debug
local io         = io
local pairs      = pairs
local ipairs     = ipairs
local math       = math
local os         = os
local print      = print
local pcall      = pcall
local xpcall     = xpcall
local rawget     = rawget
local rawset     = rawset
local select     = select
local string     = string
local table      = table
local tonumber   = tonumber
local tostring	 = tostring
local error      = error
local type       = type
local unpack     = unpack
local setmetatable = setmetatable
local getmetatable = getmetatable
local ngx = ngx


local ngx_shared  = ngx.shared;
local string_sub  = string.sub
local string_gsub = string.gsub
local string_format = string.format

local log       = require("modules.commhm.log");
local ns_time   = require("modules.commhm.time");
local uu        = require("modules.commhm.utils");

local table_insert = table.insert
local ngx_sleep = ngx.sleep
local ngx_now   = ngx.now

-------------------------------------------------------------------------------


-- SSDB MGR类
-- _VERSION = '0.12.1'
local _M = {}
local mt = { __index = _M }


--CWorkerStatistic:new(  "scan_map", { time=30, check_time=10, reset_by_total=10000, reset_by_time=1 } )
function _M.new(self, name_, pp_ )
	log.debug( log.fast() and "call ssdbMgr:new" );
	local ins_ = {
		name = name_,    --统计名字
		total = 0,       --总调用次数

		last_time  = 0,                      --最后打印时间

		check_time = pp_.check_time or 10,   --打印统计检查间隔
		time       = pp_.time       or 30,   --打印统计间隔

		reset_by_total = pp_.reset_by_total,   --达到多少次就清零
		reset_by_time  = pp_.reset_by_time,    --1=达到self.time就清零

		data = {},  --统计信息
	};
    return setmetatable(ins_, mt);
end



--增加一个上报项目
function _M.add( self, k, v )
	if  not self.data[k] then
		self.data[k] = 0
	end
	self.data[k] = self.data[k] + (v or 1)

	self.total = self.total + 1
	if  self.total % self.check_time == 0 then
		self:try_log()
	end

end



--打印统计日志
function _M.try_log(self)
	local  now_ = uu.now()
	local int_ = now_ - self.last_time
	if  int_ >= self.time then
		self.last_time = now_
		local str_ = ""
		for k, v in pairs(self.data) do
			str_ = str_ .. k .. "=" .. v .. "|"
		end
		log.day_list_simple( self.name, "tj", ngx.worker.id(), int_, self.total, str_ )

		if  self.reset_by_total and self.total >= self.reset_by_total then
			self.data = {}
		elseif  self.reset_by_time == 1 then
			self.data = {}
		else
			--不清理
		end
	end
end


return _M;
